﻿namespace FFF.Test.Application.Repositories.FW
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    using Abp.Domain.Repositories;
    using Abp.EntityFrameworkCore;
    using Abp.ObjectMapping;
    using Abp.UI;
    using AutoMapper.QueryableExtensions;
    using Microsoft.EntityFrameworkCore;
    using FFF.Test.Application.Repositories.FW;
    using FFF.Test.DataAccess.Framework;
    using FFF.Test.Entity.FW;
    using FFF.Test.Entity.FW.Dto;
    using FFF.Test.Entity.FW.View;
    using FFF.Test.Util.Web;
    using Ydm.Extensions;
    using Ydm.Helper;

    /// <summary>
    /// 用户模块配置表仓储
    /// </summary>
    public class FWUserFunctionSetRepository :
        YdmAbpRepositoryBase<FWUserFunctionSetEntity, Guid, FWUserFunctionSetCreateInputDto, FWUserFunctionSetUpdateInputDto, FWUserFunctionSetDto, ViewFWUserFunctionSet, ViewFWUserFunctionSet>,
        IFWUserFunctionSetRepository
    {
        private readonly IObjectMapper _objectMapper;

        /// <summary>
        /// Initializes a new instance of the <see cref="FWUserFunctionSetRepository"/> class.
        /// 仓储构造方法
        /// </summary>
        /// <param name="dbContextProvider">对应数据库的对象</param>
        /// <param name="objectMapper">自动映射对象</param>
        public FWUserFunctionSetRepository(
            IDbContextProvider<MyDbContext> dbContextProvider,
            IObjectMapper objectMapper
            )
            : base(dbContextProvider, objectMapper)
        {
            this._objectMapper = objectMapper;
        }

        /// <summary>
        /// 创建用户设置模块
        /// </summary>
        /// <param name="input">inputdto</param>
        /// <returns>输出dto</returns>
        public override async Task<FWUserFunctionSetDto> CreateByDtoAsync(FWUserFunctionSetCreateInputDto input)
        {
            if (input.IsSiteInner == 0)
            {
                // 获取站点的 favicon
                Uri uri = new Uri(input.UserFunctionSetUrl);
                Uri faviconUrl = new Uri(uri.Scheme + "://" + uri.Host + "/favicon.ico");
                string localAddress = $@"/down/favicons/{uri.Host}/favicon.ico";
                string localPath = Server.MapPath("~" + localAddress);
                if (!File.Exists(localPath))
                {
                    using (HttpClient client = new HttpClient())
                    {
                        try
                        {
                            client.Timeout = TimeSpan.FromSeconds(3);
                            byte[] urlContents = client.GetByteArrayAsync(faviconUrl).Result;
                            string dir = Path.GetDirectoryName(localPath);
                            if (!Directory.Exists(dir))
                            {
                                Directory.CreateDirectory(dir);
                            }

                            using (FileStream fs = new FileStream(localPath, FileMode.CreateNew))
                            {
                                fs.Write(urlContents, 0, urlContents.Length);
                            }

                        }
                        catch (Exception ex)
                        {
                            localAddress = "/favicon.ico";
                        }
                    }
                }

                input.UserFunctionSetSiteIcon = localAddress;
            }

            // 判断是否存在数据 存在重复的不用保存
            var setQuery = base.GetAll()
                .Where(x => x.UserGUID == input.UserGUID && x.UserFunctionSetUrl == input.UserFunctionSetUrl);

            if (await setQuery.AnyAsync())
            {
                // 更新创建时间 用来排序用
                await setQuery.UpdateFromQueryAsync(x => new FWUserFunctionSetEntity { CreateTime = DateTime.Now });
                var setDto = await setQuery.ProjectTo<FWUserFunctionSetDto>().FirstOrDefaultAsync();
                return setDto;
            }

            input.FunctionSetPinYin = YdmPinYinHelper.GetPinYin(input.UserFunctionSetName).Replace(" ", string.Empty);
            input.FunctionSetFirstLeShort = YdmPinYinHelper.GetPinYinFirstLetter(input.UserFunctionSetName);

            return await base.CreateByDtoAsync(input);
        }

        /// <summary>
        /// 更新的dto
        /// </summary>
        /// <param name="input">输入对象</param>
        /// <returns>展示的Dto</returns>
        /// <remarks>ydm 2020-02-01</remarks>
        public override Task<FWUserFunctionSetDto> UpdateByDtoAsync(FWUserFunctionSetUpdateInputDto input)
        {
            if (!input.UserFunctionSetName.IsNullOrEmpty())
            {
                input.FunctionSetPinYin = YdmPinYinHelper.GetPinYin(input.UserFunctionSetName).Replace(" ", string.Empty);
                input.FunctionSetFirstLeShort = YdmPinYinHelper.GetPinYinFirstLetter(input.UserFunctionSetName);
            }

            return base.UpdateByDtoAsync(input);
        }

    }
}
